import React, { useRef, useState } from 'react';
import { ProDescriptions, ProDescriptionsActionType } from '@ant-design/pro-components';
import { Button, Popconfirm } from 'antd';
import {
  distributeMyKeyUsingGet,
  getLoginUserUsingGet,
} from '@/services/sutongapi-backend/userController';
import { useModel } from '@@/exports';

const DistributeKey: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [secretKey, setSecretKey] = useState<string>();
  const actionRef = useRef<ProDescriptionsActionType>();

  return (
    <>
      <ProDescriptions
        actionRef={actionRef}
        title="你的密钥"
        request={async () => {
          const res = await getLoginUserUsingGet();
          return {
            data: res.data || {},
            success: res.code === 0,
          };
        }}
      >
        <ProDescriptions.Item dataIndex="accessKey" label="accessKey" copyable={true} span={4} />
        <ProDescriptions.Item
          dataIndex="secretKey"
          label="secretKey"
          copyable={true}
          span={4}
          tooltip="请妥善保存，关闭此弹窗将消失"
        >
          {secretKey}
        </ProDescriptions.Item>
        <ProDescriptions.Item label="文本" valueType="option">
          <Popconfirm
            title="获取密钥"
            description="您确定要重新获取密钥吗？原先的密钥将失效"
            onConfirm={async () => {
              const res = await distributeMyKeyUsingGet();
              setSecretKey(res.data?.secretKey);
              setInitialState({
                ...initialState,
                currentUser: {
                  ...initialState?.currentUser,
                  accessKey: res.data?.accessKey,
                },
              });
              actionRef.current?.reload();
            }}
          >
            <Button type="primary">获取</Button>
          </Popconfirm>
        </ProDescriptions.Item>
      </ProDescriptions>
    </>
  );
};

export default DistributeKey;
